import Cookies from 'js-cookie'
import {getAddMsgList} from "@/api/message";
import {getFriendList} from "@/api/user";
import {Message} from "element-ui";
import tim from "@/tim";

const getDefaultState = ()=>{
  return {
    isLogin:false,  //tim是否登录
    isSDKReady:false,  // TIM SDK 是否ready
    // 保存chat侧边栏活跃的状态
    sidebarActive:Cookies.get('sidebarActive'),
    friendActive:'', // 朋友页面活跃组件
    currentFriendInfo:'', // 当前查看的朋友信息
    friendList:[], // 朋友列表
    requestMessageList:[], // 请求添加好友消息列表

    isCompleted:false, // 当前会话消息列表是否已经拉完了所有消息
    currentMessageList:[], // 当前聊天记录
    nextReqMessageID:'', // 下一条消息的id
    conversationList:[], // 会话列表
    currentMemberList:[],
    currentConversation:{},  // 当前会话
    message:undefined,
  }
}

const state = getDefaultState()

const  mutations ={
  RESET_STATE: (state) => {
    // Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象
    Object.assign(state, getDefaultState())
  },
  SET_SIDEBAR_ACTIVE:(state,active)=>{
    state.sidebarActive = active
    Cookies.set('sidebarActive',active)
  },
  SET_FRIEND_ACTIVE:(state,active)=>{
    state.friendActive = active
  },
  SET_CURRENT_FRIEND_INFO:(state,info)=>{
    state.currentFriendInfo = info
  },
  SET_REQUEST_MESSAGE_LIST:(state,messageList)=>{
    state.requestMessageList = messageList
  },
  ADD_REQUEST_MESSAGE_LIST:(state,message)=>{
    state.requestMessageList.push(message)
  },
  REMOVE_REQUEST_MESSAGE:(state,index)=>{
    state.requestMessageList.splice(index,1)
  },
  SET_FRIEND_LIST:(state,friendList)=>{
    state.friendList = friendList
  },
  ADD_FRIEND_LIST:(state,friend)=>{
    state.friendList.push(friend)
  },
  // 设置tim 登录状态
  set_isLogin:(state,isLogin)=>{
    state.isLogin = isLogin
  },
  // 设置tim SDK 准备状态
  set_isSDKReady:(state,isSDKReady)=>{
    state.isSDKReady = isSDKReady
  },
  // 显示提示消息
  showMessage(state,options){
    if(state.message){
      state.message.close()
    }
    state.message = Message({
      message:options.message,
      type:options.type||'success',
      duration:options.duration||2000,
      offset:40
    })
  },
  //重置当前会话列表
  resetCurrentMemberList(state) {
    console.log("重置当前的会话列表")
    state.currentMemberList = []
  },
  // 修改当前会话
  updateCurrentConversation(state, conversation) {
    console.log("更新当前会话："+conversation.conversationID)
    state.currentConversation = conversation
    state.currentMessageList = [] // 清空聊天列表
    state.nextReqMessageID = '' // 清空下一次消息加载的id
    state.isCompleted = false // 初始化消息加载完成标识
  },
  /**
   * 更新会话列表
   * @param state
   * @param conversationList
   */
  updateConversationList(state,conversationList){
    if(state.isLogin){
      state.conversationList = conversationList
    }
  },
  // 设置会话列表
  setConversationList(state,conversationList){
    state.conversationList = conversationList
  },
  pushCurrentMessageList(state,data){
    console.log("将当前消息插入到当前会话的消息列表中")
    // 还没有当前会话不做任何处理
    if(!state.currentConversation.conversationID){
      return
    }
    if(Array.isArray(data)){
      const result = data.filter(item=>item.conversationID === state.currentConversation.conversationID)
      state.currentMessageList = [...state.currentMessageList,...result]
    }else if(data.conversationID === state.currentConversation.conversationID){
      state.currentMessageList = [...state.currentMessageList,data]
    }
  }
}

const getters = {

}

const actions = {
  // 获取请求添加好友消息列表
  getRequestMessageList({commit}){
    new Promise((resolve,reject)=>{
      getAddMsgList().then(res=>{
        let messageList = res.content.messageList;
        commit('SET_REQUEST_MESSAGE_LIST', messageList);
        console.log("请求ADD-FRIEND消息成功！")
        resolve(messageList)
      }).catch(err=>{
        reject(err)
      })
    })
  },
  // 获取朋友列表
  getFriendList({commit}){
    new Promise((resolve,reject)=>{
      getFriendList().then(res=>{
        let friendList = res.content.friendList;
        commit('SET_FRIEND_LIST',friendList)
        console.log(res)
        resolve(friendList)
      }).catch(err=>reject(err))
    })
  },

  // 获取tim 中的会话列表
  getConversationListTIM({state,commit}){
    new Promise((resolve,reject)=>{
      console.log("isSDK状态："+state.isSDKReady)
      if(state.isSDKReady){
        // 请求会话列表
        tim.getConversationList().then(res=>{
          console.log(res.data.conversationList)
          // 保存会话列表
          commit('setConversationList',res.data.conversationList) // 初始化会话列表
        }).catch(err=>{
          commit('showMessage',{
            type:'error',
            message:err.message
          })
          reject()
        })
      }
      resolve()
    })
  },
  // 登录到tim
  loginTIM({commit,rootGetters}){
    console.log("开始登录TIM："+rootGetters.id)
    console.log("开始登录TIM userSign："+rootGetters.userSign)
    new Promise((resolve,reject)=>{
      if(!rootGetters.userSign){
        console.log("缺少tim签名")
        resolve()
        return
      }
      console.log("登录tim userID："+rootGetters.id+" ---------- userSig："+rootGetters.userSign)
      tim.login({
        userID:rootGetters.id,
        userSig:rootGetters.userSign
      }).then(res=>{
        console.log("登录TIM成功")
        commit('set_isLogin', true);
        commit('showMessage',{
          type:'success',
          message:'登录成功'
        })
        resolve()
      }).catch(err=>{
        console.log("tim登录出错")
        console.log(err)
        commit('showMessage',{
          message:'登录失败：'+err.message,
          type:'error'
        })
        reject()
      })
    })
  },
  /**
   * 切换会话
   * 执行时机 切换会话时
   * @param state
   * @param commit
   * @param dispatch
   * @param conversationID
   * @returns {*}
   */
  checkoutConversation({state,commit,dispatch},conversationID){
    console.log("开始切换会话：" + conversationID);
    commit('resetCurrentMemberList')
    // 切换会话前，将切换前的会话进行已读上报
    if(state.currentConversation.conversationID){
      dispatch('setCurrentConversationMessageRead')
    }
    // 待切换的会话也进行已读上报，也就是目标会话
    tim.setMessageRead({conversationID})
    // 根据指定的会话id获取对应的会话信息
    return tim.getConversationProfile(conversationID).then(({data})=>{
      // 更新当前会话
      commit('updateCurrentConversation',data.conversation)

      // dispatch('getConversationListTIM') // 获取会话列表
      dispatch('getMessageList',conversationID) // 获取消息列表

      return Promise.resolve()
    })
  },
  /**
   * 设置当前会话消息为已读
   * @param state
   */
  setCurrentConversationMessageRead({state}){
    console.log("设置当前会话消息已读")
    tim.setMessageRead({conversationID:state.currentConversation.conversationID})
  },
  /**
   * 获取消息列表
   * @param context
   * @param conversationID
   */
  getMessageList(context,conversationID){
    console.log("开始获取消息列表："+conversationID)
    console.log("开始获取消息列表："+context.state.isCompleted)
    if(context.state.isCompleted){
      context.commit('showMessage',{
        message:"已经没有更多的历史消息了哦",
        type:'info'
      })
      return
    }
    const {nextReqMessageID,currentMessageList} = context.state
   return tim.getMessageList({conversationID,nextReqMessageID,count:15}).then(req=>{
      console.log(req.data.messageList)
      // 更新messageID ，下拉获取更多消息时需要用到
      context.state.nextReqMessageID = req.data.nextReqMessageID
      context.state.isCompleted = req.data.isCompleted
      // 更新当前消息列表，从头部插入
      context.state.currentMessageList = [...req.data.messageList,...currentMessageList]
      console.log("获取到的消息条数："+req.data.messageList.length)
     console.log("消息列表获取成功，是否获取完全部消息：" + context.state.isCompleted)
     return Promise.resolve()
    })
  },


}


export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions,
}
